/**
 * @(#)DataSourceFactory.java, 2008-4-30.
 * Copyright 2008  Program Analysis Research Group(PARG),Institute of Software, Peking University.
 * All rights reserved.
 */
package edu.pku.sei.pgie.persistence.dao;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import edu.pku.sei.pgie.Activator;
import edu.pku.sei.pgie.ui.preferences.PreferenceConstants;

import org.eclipse.jface.preference.IPreferenceStore;

public class DataSourceFactory {
    static DataSource dataSourceInst;

    static String driver;

    static String url;

    static String user;

    static String password;

    private static void updateConfiguration() {
        IPreferenceStore store = Activator.getDefault().getPreferenceStore();
        driver = store
                .getString(PreferenceConstants.DATABASE_DRIVER_PREFERENCE);
        url = store.getString(PreferenceConstants.DATABASE_URL_PREFERENCE);
        user = store.getString(PreferenceConstants.DATABASE_USER_PRERFERENCE);
        password = store
                .getString(PreferenceConstants.DATABASE_PASSWORD_PREFERENCE);

    }

    public static synchronized DataSource getDataSource() {
        if (dataSourceInst == null) {
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setInitialSize(10);
            updateConfiguration();
            basicDataSource.setDriverClassName(driver);
            basicDataSource.setUrl(url);
            basicDataSource.setUsername(user);
            basicDataSource.setPassword(password);
            dataSourceInst = basicDataSource;
        }
        return dataSourceInst;
    }

    public static synchronized void reConnect() {
        if (dataSourceInst == null)
            return;
        updateConfiguration();
        try {
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setInitialSize(10);
            basicDataSource.setDriverClassName(driver);
            basicDataSource.setUrl(url);
            basicDataSource.setUsername(user);
            basicDataSource.setPassword(password);
            dataSourceInst = basicDataSource;
        } catch (Exception e) {}
    }
}
